"""
逻辑接口层
    银行相关业务的接口
"""
from sys import flags
from db import db_handler
import time
from lib import common
#产生一个日志对象
logginger = common.get_log("bank")

#查询余额接口
def select_banlace(user_name):
    user_dic = db_handler.select(user_name)
    return user_dic.get("balance")

#提现功能
def getmoney(loginer,money):
    if money > 5000:
        return False,f"提现金额超过5000，提取失败"
    user_dic = db_handler.select(loginer)
    yue = user_dic.get("balance")
    money2 = money*1.01
    if yue >=money2:
        backmoeny = yue - money2
        user_dic["balance"] = backmoeny
        flow = f"用户{loginer}成功提现[{money}]元,扣除手续费[{money2-float(money)}]元,剩余[{backmoeny:=^11}]元"
        logginger.info(flow)
        user_dic["flow"].append(flow)
        db_handler.save(user_dic)
        return True,flow
    return False,f"用户{loginer}余额不足,请重新输入!"

#还款功能
def backmoney(loginer,money):
    user_dic = db_handler.select(loginer)
    yue = user_dic.get("balance")
    yue_update = yue + money
    user_dic["balance"] = yue_update
    flow = f"用户{loginer}还款{money}元成功,总余额{yue_update}元"
    logginger.info(flow)
    user_dic["flow"].append(flow)
    db_handler.save(user_dic)
    return True,flow


#转账功能
def transfer(loginer,people,money):
    user_dic_people = db_handler.select(people)
    if user_dic_people == None:
        return False,f"用户\"{people}\"不存在！请重新输入"
    user_dic_loginer = db_handler.select(loginer)
    money_loginer = int(user_dic_loginer.get("balance"))
    money_people = int(user_dic_people.get("balance"))
    if money_loginer < money:
        return False,f"用户{loginer}余额不足,转账失败"
    money_loginer_transfer = money_loginer - money
    money_people_transfer = money_people + money
    user_dic_loginer["balance"] = money_loginer_transfer
    user_dic_people["balance"] = money_people_transfer
    flow2 = f"用户{people}成功从用户{loginer}接受{money}元，余额{money_people_transfer}"
    flow1= f"用户{loginer}成功向用户{people}转账{money}元，余额{money_loginer_transfer}"
    logginger.info(flow1)
    logginger.info(flow2)
    user_dic_loginer["flow"].append(flow1)
    user_dic_people["flow"].append(flow2)
    db_handler.save(user_dic_loginer)
    db_handler.save(user_dic_people)
    return True,flow1

#流水功能
def check_flow(loginer):
    user_dic = db_handler.select(loginer)
    if user_dic["flow"]:
        return True,user_dic["flow"]
    else:
        return False,f"用户{loginer}没有流水"

#购物车支付功能
def pay_car(loginer,zongjia,names):
    user_dic = db_handler.select(loginer)
    yue = user_dic["balance"]
    if yue <zongjia:
        return False,"余额不足，支付失败"
    shengyu_money = yue-zongjia
    user_dic["balance"] = shengyu_money
    times = time.strftime("%Y-%m-%d %H-%M-%S %p",time.localtime())
    flow = f"{times}:用户{loginer}支付{zongjia}元,购买了{names},余额{shengyu_money}"
    logginger.info(flow)
    user_dic["flow"].append(flow)
    db_handler.save(user_dic)
    return True,flow